package com.talos.ums.service.roleresource;

import com.talos.framework.common.pojo.PageResult;
import com.talos.framework.common.util.object.BeanUtils;
import com.talos.ums.controller.admin.roleresource.vo.UmsRoleResourcePageReqVO;
import com.talos.ums.controller.admin.roleresource.vo.UmsRoleResourceSaveReqVO;
import com.talos.ums.dal.dataobject.roleresource.UmsRoleResourceDO;
import com.talos.ums.dal.mysql.roleresource.UmsRoleResourceMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import static com.talos.framework.common.exception.enums.GlobalErrorCodeConstants.DATA_NOT_FOUND;
import static com.talos.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 角色菜单关联表 Service 实现类
 *
 * @author ${table.author}
 */
@Service
@Validated
public class UmsRoleResourceServiceImpl implements UmsRoleResourceService {

    @Resource
    private UmsRoleResourceMapper roleResourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createRoleResource(UmsRoleResourceSaveReqVO createReqVO) {
        // 插入
        UmsRoleResourceDO roleResource = BeanUtils.toBean(createReqVO, UmsRoleResourceDO.class);
        roleResourceMapper.insert(roleResource);
        // 返回
        return roleResource.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRoleResource(UmsRoleResourceSaveReqVO updateReqVO) {
        // 校验存在
        validateRoleResourceExists(updateReqVO.getId());
        // 更新
        UmsRoleResourceDO updateObj = BeanUtils.toBean(updateReqVO, UmsRoleResourceDO.class);
        roleResourceMapper.updateById(updateObj);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRoleResource(Long id) {
        // 校验存在
        validateRoleResourceExists(id);
        // 删除
        roleResourceMapper.deleteById(id);
    }

    private void validateRoleResourceExists(Long id) {
        if (roleResourceMapper.selectById(id) == null) {
            throw exception(DATA_NOT_FOUND);
        }
    }

    @Override
    public UmsRoleResourceDO getRoleResource(Long id) {
        return roleResourceMapper.selectById(id);
    }

    @Override
    public PageResult<UmsRoleResourceDO> getRoleResourcePage(UmsRoleResourcePageReqVO pageReqVO) {
        return roleResourceMapper.selectPage(pageReqVO);
    }

}
